package com.eds.mall.search.service.impl;

import com.eds.common.dto.es.SkuESModel;
import com.eds.mall.search.config.ElasticSearchConfigtion;
import com.eds.mall.search.constant.ESConstant;
import com.eds.mall.search.service.ElasticSearchService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author zz_code
 * @data 2024/5/9 21:26
 */
@Service
public class ElasticSearchServiceImpl implements ElasticSearchService {

    @Autowired
    RestHighLevelClient client;

    /**
     * 实现上架数据存储到ES的操作
     * 批量存储
     * @param skuESModels
     * @return
     */
    @Override
    public Boolean productStatusUp(List<SkuESModel> skuESModels) throws IOException{
        // 单条数据存储方式
        //IndexRequest indexRequest = new IndexRequest();
        //indexRequest.source("",XContentType.JSON) ; // 存储JSON字符串
        // client.index(indexRequest, ElasticSearchConfigtion.COMMON_OPTIONS);   单一数据存储的方法

        // 以下为多条存储方式，就是将 IndexRequest添加到BulkRequest中
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuESModel obj : skuESModels) {
            IndexRequest indexRequest = new IndexRequest(ESConstant.PRODUCT_INDEX);
            indexRequest.id(obj.getSkuId().toString());

            ObjectMapper mapper = new ObjectMapper();
            String objStr = mapper.writeValueAsString(obj);
            indexRequest.source(objStr, XContentType.JSON);

            bulkRequest.add(indexRequest);
        };

        // bulk 是批量存储方法
        BulkResponse bulk = client.bulk(bulkRequest, ElasticSearchConfigtion.COMMON_OPTIONS);

        return !bulk.hasFailures();
    }
}
